package com.demo.schedule.medicine;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import com.demo.entity.Message;
import com.demo.entity.MessageRule;
import com.demo.entity.VtePreventiveDoctorAdvice;
import com.demo.enums.MessageRuleLoopWarningEnum;
import com.demo.mapper.MessageMapper;
import org.springframework.context.ApplicationContext;

import java.util.Date;
import java.util.Objects;

public class MedicineRemindUtil {

    /**
     * 获取药物提醒的分钟数
     *
     * @param doctorAdvice
     * @return
     */
    public static Long getMedicineRemindWakeupTime(VtePreventiveDoctorAdvice doctorAdvice, MessageRule messageRule, ApplicationContext applicationContext) {
        Date nowDate = DateUtil.date(System.currentTimeMillis());
        Date createdTime = doctorAdvice.getCreatedTime();
        long betweenDay = DateUtil.betweenDay(createdTime, nowDate, true);
        Date todaySignDate = DateUtil.offsetDay(createdTime, Integer.parseInt(String.valueOf(betweenDay)));//将药物提醒日期偏移到今天
        long betweenMinute = 0L;

        Message medicineRemindMessage = null;
        if (Objects.equals(messageRule.getIsLoopWarning().intValue(), MessageRuleLoopWarningEnum.YES.getValue())) {
            // 循环提醒 - 判断进行今天是否已经提醒过
            Date beginDate = DateUtil.beginOfDay(nowDate);
            medicineRemindMessage = applicationContext.getBean(MessageMapper.class).queryByCondition(doctorAdvice.getDoctorAdviceId(), beginDate, nowDate);
        } else {
            // 一次提醒-判断是否已经提醒过
            medicineRemindMessage = applicationContext.getBean(MessageMapper.class).queryByDoctorAdviceId(doctorAdvice.getDoctorAdviceId());
        }

        if (medicineRemindMessage != null || betweenDay == 0) { // betweenDay == 0 ： 开药时间就是今天
            //偏移到下一个周期提醒
            Date remindDate = DateUtil.offsetDay(todaySignDate, messageRule.getCycleInterval());
            betweenMinute = DateUtil.between(nowDate, remindDate, DateUnit.MINUTE);
        } else {
            if (todaySignDate.getTime() <= nowDate.getTime()) {
                return betweenMinute;
            }
            betweenMinute = DateUtil.between(nowDate, todaySignDate, DateUnit.MINUTE);
        }
        return betweenMinute;
    }
}
